package com.waverider.promotion.web.bg.screen;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.servlet.ModelAndView;

import com.iacrqq.util.StringUtil;
import com.taobao.api.domain.Item;
import com.waverider.promotion.biz.manager.ItemManager;
import com.waverider.promotion.model.BaseQueryModel;
import com.waverider.promotion.model.ItemQueryModel;
import com.waverider.promotion.model.PromotionItem;
import com.waverider.promotion.model.ResultModel;
import com.waverider.promotion.web.AbstractLoginedController;

public class ItemList extends AbstractLoginedController {

	private static final Log logger = LogFactory.getLog(ItemList.class);

	private ItemManager itemManager;

	@Override
	protected ModelAndView handleLogined(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Long currentPage = null;
		String strCurrentPage = request.getParameter("current_page");
		String goodsTitle = request.getParameter("goodsTitle");
		if (StringUtil.isBlank(strCurrentPage)) {
			currentPage = 1L;
		} else {
			try {
				currentPage = Long.valueOf(strCurrentPage);
			} catch (NumberFormatException e) {
				logger.error(e);
				currentPage = 1L;
			}
		}

		ItemQueryModel queryModel = ItemQueryModel.buildQueryModel(currentPage,
				BaseQueryModel.DEFAULT_PAGE_SIZE);
		if (StringUtils.isNotBlank(goodsTitle)) {
			queryModel.setGoodsTitle(goodsTitle);
		}
		ResultModel<Item> resultModel = itemManager.getItemList(
				getSessionKey(request.getSession()), queryModel);

		List<Item> promotionItemList = new LinkedList<Item>();
		List<Item> itemList = resultModel.getItemList();

		if (itemList != null && !itemList.isEmpty()) {
			for (Item item : itemList) {
				promotionItemList.add(item2PromotionItem(item));
			}
		}

		resultModel.setItemList(promotionItemList);

		ModelAndView mv = new ModelAndView("bg/itemList");
		Map<String, Object> context = mv.getModel();
		context.put("resultModel", resultModel);
		context.put("pageNo", 1);

		return mv;
	}

	private PromotionItem item2PromotionItem(Item item) {
		PromotionItem promotionItem = new PromotionItem();

		BeanUtils.copyProperties(item, promotionItem);
		promotionItem.setPromotion(itemManager.getPromotionByGoodsId(item
				.getNumIid()));

		return promotionItem;
	}

	public void setItemManager(ItemManager itemManager) {
		this.itemManager = itemManager;
	}
}
